//
//  NewCategoryView.swift
//  MyDiary2025
//
//  Created by 罗万能 on 2025/6/28.
//


import SwiftUI
import PhotosUI
import SwiftData

struct NewCategoryView: View {
    @Environment(\.dismiss) private var dismiss
    @Environment(\.modelContext) private var modelContext
    
    @State private var categoryName: String = ""
    @State private var categoryDescription: String = ""
    @State private var selectedColor: Color = .primary
    @State private var selectedImage: UIImage?
    @State private var showingImagePicker: Bool = false
    @State private var selectedMedia: PHAsset?
    
    // 颜色选项
    let colorOptions: [Color] = [
        .red, .green, .blue, .yellow, .purple, .orange,
        .pink, .teal, .cyan, .indigo, .mint, .brown
    ]
    
    var body: some View {
        
        ScrollView{
            VStack(alignment: .leading, spacing: 12) {
                // 分类名称输入
                TextField("输入分类名称", text: $categoryName)
                    .foregroundStyle(selectedColor)
                    .textFieldStyle(.roundedBorder)
                    .font(.title2.bold())
//                    .padding()
//                    .background(
//                        RoundedRectangle(cornerRadius: 15)
//                            .fill(Color("back"))
//                            .shadow(radius: 5)
//                    )
                
                // 分类描述输入
                TextEditor(text: $categoryDescription)
                    .foregroundStyle(selectedColor)
                    .textEditorStyle(.automatic)
                    .font(.body)
                    .frame(minHeight: 200)
//                    .padding()
//                    .background(
//                        RoundedRectangle(cornerRadius: 15)
//                            .fill(Color("back"))
//                            .shadow(radius: 5)
//                    )
                
                // 颜色选择
                VStack(alignment: .leading, spacing: 20) {
                    Text("选择颜色")
                        .font(.headline)
                        .padding(.leading, 20)
                    
                    ScrollView(.horizontal){
                        HStack{
                            ForEach(colorOptions, id: \.self) { color in
                                Circle()
                                    .fill(color)
                                    .frame(width: selectedColor == color ? 50 : 36, height: selectedColor == color ? 50 : 36)
                                
                                    .overlay(
                                        
                                        Circle()
                                            .stroke(selectedColor == color ? Color.primary : .clear, lineWidth: 2)
                                    )
                                    .onTapGesture {
                                        withAnimation{
                                            selectedColor = color
                                        }
                                    }
                            }
                        }
                        .padding(.horizontal)
                        
                    }
                    .padding()
                    .background(
                                        RoundedRectangle(cornerRadius: 15)
                                            .fill(Color("back"))
                                            .shadow(radius: 5)
                                            .padding(.horizontal)
                                    )
                    .scrollIndicators(.hidden)
                }
                .padding(.bottom,12)
//                .background(
//                    RoundedRectangle(cornerRadius: 15)
//                        .fill(Color("back"))
//                        .shadow(radius: 5)
//                        .padding(.horizontal)
//                )
                
                // 图片选择
                VStack(alignment: .leading) {
                    Text("选择图片 (可选)")
                        .font(.headline)
                        .padding(.leading)
                    
                    if let image = selectedImage {
                        Image(uiImage: image)
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(maxHeight: 200)
                            .cornerRadius(15)
                            .shadow(radius: 5)
                            .padding()
                    } else {
                        ZStack {
                            RoundedRectangle(cornerRadius: 15)
                                .fill(Color("placeholderground"))
                                .frame(maxHeight: 200)
                                .shadow(radius: 5)
                            
                            VStack {
                                Image(systemName: "photo.fill")
                                    .font(.title)
                                    .foregroundColor(.gray)
                                Text("点击添加图片")
                                    .font(.subheadline)
                                    .foregroundColor(.gray)
                            }
                            .padding()
                        }
                        .padding()
                    }
                    
                    Button("从相册选择图片") {
                        showingImagePicker = true
                        selectedMedia = nil
                    }
                    .font(.headline)
                    .foregroundColor(.white)
                    .padding()
                    .background(
                        Capsule()
                            .fill(Color("accentColor"))
                    )
                    .padding()
                }
                .background(
                    RoundedRectangle(cornerRadius: 15)
                        .fill(LinearGradient(
                            colors: [Color.title, selectedColor],
                            startPoint: .top, endPoint: .bottom))
                        .shadow(radius: 5)
                )
            }            .padding()
            .navigationTitle("新建分类")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("取消") {
                        dismiss()
                    }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("保存") {
                        saveCategory()
                    }
                    .disabled(categoryName.isEmpty)
                }
            }
            .sheet(isPresented: $showingImagePicker) {
                                PhotoPicker(
                                    selectedMedia: $selectedMedia,
                                    onImageSelected: { image in
                                        selectedImage = image
                                    },
                                    onVideoSelected: { _ in }
                                )
            }
            Spacer()
            
            // 保存按钮
            Button("创建分类") {
                saveCategory()
            }
            .font(.title3.bold())
            .foregroundColor(.title)
            .padding()
            .frame(maxWidth: .infinity)
            .background(
                Capsule()
                    .fill(Color("back"))
                    .shadow(radius: 10)
            )
            .padding(.horizontal)
            .disabled(self.categoryName.isEmpty)
            Button("取消") {
                cancle()
            }
            .font(.title3.bold())
            .foregroundColor(.red)
            .padding()
            .frame(maxWidth: .infinity)
            .background(
                Capsule()
                    .fill(Color("back"))
                    .shadow(radius: 10)
            )
            .padding(.horizontal)
            .disabled(self.categoryName.isEmpty)
        }
        .background(LinearGradient(
            colors: [Color.title, selectedColor],
            startPoint: .topLeading, endPoint: .bottomTrailing))
    }
    
    
    // 保存分类
    private func saveCategory() {
        let newCategory = CategoryModel(
            id: UUID(),
            categoryName: categoryName,
            categoryImage: selectedImage?.pngData(),
            categoryDescription: categoryDescription,
            categoryColor: selectedColor
        )
        
        modelContext.insert(newCategory)
        dismiss()
    }
    private func cancle(){
        self.categoryName = ""
        self.selectedColor = Color.primary
        dismiss()
    }
}

#Preview {
    NewCategoryView()
}
